﻿using System;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;

namespace wojilu
{
    /// <summary>
    /// 数据验证处理
    /// </summary>
    public static class DataSecurity
    {
        // Fields
        private static Random rnd = new Random();

        #region URL编码
        /// <summary>
        /// 对 URL 字符串进行编码,系统自带的。
        /// </summary>
        /// <param name="theString">要编码的文本</param>
        /// <returns>一个已编码的字符串</returns>
        public static string UrlEncodes(this string theString)
        {
            return HttpUtility.UrlEncode(theString);
        }

        /// <summary>
        /// 将已经为在 URL 中传输而编码的字符串转换为解码的字符串,系统自带的。
        /// </summary>
        /// <param name="theString">要解码的字符串</param>
        /// <returns>一个已解码的字符串</returns>
        public static string UrlDecodes(this string theString)
        {
            return HttpUtility.UrlDecode(theString);
        }

        /// <summary>
        ///  对要传递的中文参数进行编码
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string SetUrlEncoding(this string str)
        {
            return HttpContext.Current.Server.UrlEncode(str);
        }

        /// <summary>
        /// 对传递过来的参数进行解码为中文
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string GetUrlEncoding(this string str)
        {
            return HttpContext.Current.Server.UrlDecode(str);
        }
        /// <summary>
        /// URL编码
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static string UrlEncode(this object value)
        {
            if (value == null)
            {
                return null;
            }
            return UrlEncode(value.ToString());
        }

        public static string UrlEncode(this string weburl)
        {
            if (string.IsNullOrEmpty(weburl))
            {
                return null;
            }
            return Regex.Replace(weburl, @"[^a-zA-Z0-9,-_\.]+", new MatchEvaluator(DataSecurity.UrlEncodeMatch));
        }

        public static string UrlEncode(this string weburl, bool systemEncode)
        {
            if (string.IsNullOrEmpty(weburl))
            {
                return null;
            }
            if (systemEncode)
            {
                return HttpUtility.UrlEncode(weburl);
            }
            return UrlEncode(weburl);
        }

        private static string UrlEncodeMatch(Match match)
        {
            string str = match.ToString();
            if (str.Length < 1)
            {
                return str;
            }
            StringBuilder builder = new StringBuilder();
            foreach (char ch in str)
            {
                if (ch > '\x007f')
                {
                    builder.AppendFormat("%u{0:X4}", (int)ch);
                }
                else
                {
                    builder.AppendFormat("%{0:X2}", (int)ch);
                }
            }
            return builder.ToString();
        }

        #endregion

        #region 常用字符串Html编码/解码

        /// <summary>
        /// 将字符串转换为 HTML 编码的字符串,系统自带的。
        /// </summary>
        /// <param name="theString">要编码的字符串</param>
        /// <returns>一个已编码的字符串</returns>
        public static string HtmlEncodes(this string theString)
        {
            return HttpUtility.HtmlEncode(theString);
        }

        /// <summary>
        /// 将字符串转换为 HTML 编码的字符串并将输出作为 System.IO.TextWriter 输出流返回,系统自带的。
        /// </summary>
        /// <param name="theString">要编码的字符串</param>
        /// <param name="output">System.IO.TextWriter 输出流</param>
        public static void HtmlEncodes(this string theString, TextWriter output)
        {
            HttpUtility.HtmlEncode(theString, output);
        }

        /// <summary>
        /// 将已经为 HTTP 传输进行过 HTML 编码的字符串转换为已解码的字符串,系统自带的。
        /// </summary>
        /// <param name="theString">要解码的字符串</param>
        /// <returns>一个已解码的字符串</returns>
        public static string HtmlDecodes(this string theString)
        {
            return HttpUtility.HtmlDecode(theString);
        }

        /// <summary>
        /// 将已经过 HTML 编码的字符串转换为已解码的字符串并将其发送给 System.IO.TextWriter 输出流,系统自带的。
        /// </summary>
        /// <param name="theString">要解码的字符串</param>
        /// <param name="output">System.IO.TextWriter 输出流</param>
        public static void HtmlDecodes(this string theString, TextWriter output)
        {
            HttpUtility.HtmlDecode(theString, output);
        }

        /// <summary>
        /// 字符串解码回原状态
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static string HtmlDecode(this object value)
        {
            if (value == null)
            {
                return null;
            }
            return HtmlDecode(value.ToString());
        }

        /// <summary>
        /// 字符串解码回原状态,解析html成 普通文本
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static string HtmlDecode(this string value)
        {
            if (!string.IsNullOrEmpty(value))
            {
                value = value.Replace("<br>", "\n");
                value = value.Replace("<br/>", "\n");
                value = value.Replace("<br />", "\n");
                value = value.Replace("&gt;", ">");
                value = value.Replace("&lt;", "<");
                value = value.Replace("&nbsp;", " ");
                value = value.Replace(" &nbsp;", " ");
                value = value.Replace("&#39;", "\'");
                value = value.Replace("&quot;", "\"");
                value = value.Replace("&amp;", "&");
            }
            return value;
        }

        /// <summary>
        /// 输出单行简介
        /// </summary>
        /// <param name="theString"></param>
        /// <returns></returns>
        public static string SimpleLineSummary(this string theString)
        {
            theString = theString.Replace("&gt;", "");
            theString = theString.Replace("&lt;", "");
            theString = theString.Replace(" &nbsp;", "  ");
            theString = theString.Replace("&quot;", "\"");
            theString = theString.Replace("&#39;", "'");
            theString = theString.Replace("<br/> ", "\r\n");
            theString = theString.Replace("\"", "");
            theString = theString.Replace("\t", " ");
            theString = theString.Replace("\r", " ");
            theString = theString.Replace("\n", " ");
            theString = Regex.Replace(theString, "\\s{2,}", " ");
            return theString;
        }

        /// <summary>
        /// 字符串编码
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static string HtmlEncode(this object value)
        {
            if (value == null)
            {
                return null;
            }
            return HtmlEncode(value.ToString());
        }

        /// <summary>
        /// 字符串编码转换成 HTML code
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static string HtmlEncode(this string str)
        {
            if (!string.IsNullOrEmpty(str))
            {
                str = str.Replace("&", "&amp;");
                str = str.Replace("<", "&lt;");
                str = str.Replace(">", "&gt;");
                str = str.Replace(" ", "&nbsp;");
                str = str.Replace("'", "&#39;");
                str = str.Replace("\"", "&quot;");
                str = str.Replace("\r\n", "<br />");
                str = str.Replace("\n", "<br />");
                str = str.Replace("\r", "<br />");
                str = str.Replace("\r\n\t", "<br />");
            }
            return str;
        }

        /// <summary>
        /// 标签解码
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static string PELabelDecode(this string value)
        {
            if (!string.IsNullOrEmpty(value))
            {
                value = value.Replace("ζ#123;", "{");
                value = value.Replace("ζ#125;", "}");
            }
            return value;
        }

        public static string InputTexts(this string text)
        {
            if (string.IsNullOrEmpty(text))
            {
                return string.Empty;
            }
            text = Regex.Replace(text, @"[\s]{2,}", " ");
            text = Regex.Replace(text, @"(<[b|B][r|R]/*>)+|(<[p|P](.|\n)*?>)", "\n");
            text = Regex.Replace(text, @"(\s*&[n|N][b|B][s|S][p|P];\s*)+", " ");
            text = Regex.Replace(text, @"<(.|\n)*?>", string.Empty);
            text = text.Replace("'", "''");
            return text;
        }

        /// <summary>
        /// 标签编码
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static string PELabelEncode(this string value)
        {
            if (!string.IsNullOrEmpty(value))
            {
                value = value.Replace("{", "ζ#123;");
                value = value.Replace("}", "ζ#125;");
                value = Regex.Replace(value, @"<!--([^>]*?#include[\s\S]*?)-->", "&lt;!--$1--&gt;", RegexOptions.Compiled | RegexOptions.IgnoreCase);
                value = value.Replace("ζ#123;PE.SiteConfig.uploaddir/ζ#125;", "{PE.SiteConfig.uploaddir/}");
                value = value.Replace("ζ#123;PE.SiteConfig.ApplicationPath/ζ#125;", "{PE.SiteConfig.ApplicationPath/}");
            }
            return value;
        }

        #endregion


        #region Xml文件编码
        /// <summary>
        /// Xml文件编码
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string XmlEncode(this string str)
        {
            if (!string.IsNullOrEmpty(str))
            {
                str = str.Replace("&", "&amp;");
                str = str.Replace("<", "&lt;");
                str = str.Replace(">", "&gt;");
                str = str.Replace("'", "&apos;");
                str = str.Replace("\"", "&quot;");
            }
            return str;
        }

        public static string XmlDecode(this string str)
        {
            if (!string.IsNullOrEmpty(str))
            {
                str = str.Replace("&amp;", "&");
                str = str.Replace("&lt;", "<");
                str = str.Replace("&gt;", ">");
                str = str.Replace("&apos;", "'");
                str = str.Replace("&quot;", "\"");
            }
            return str;
        }
        #endregion

        #region 过滤HTML
        /// <summary>
        /// 过滤HTML
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string LeachHTML(string str)
        {
            if (str == null | string.IsNullOrEmpty(str)) return "";
            string leachhtml = "";
            leachhtml = str.GetReplace("javascript:if(this.width>500){this.width=500};if(this.height>500){this.height=500;}", "DrawImage(this, 500, 500)");
            leachhtml = LeachExp(leachhtml, @"<\/*[^<>]*>");
            leachhtml = leachhtml.GetReplace("&nbsp;", "");
            leachhtml = leachhtml.GetReplace(" ", "");
            leachhtml = leachhtml.GetReplace("　", "");
            leachhtml = leachhtml.GetReplace(System.Environment.NewLine, "");
            leachhtml = leachhtml.GetReplace("[NextPage]", "");
            leachhtml = StringHelper.Trim(leachhtml);
            return leachhtml;
        }
        #endregion

        #region 正则过滤
        /// <summary>
        /// 正则过滤
        /// </summary>
        /// <param name="Str"></param>
        /// <param name="ExpStr"></param>
        /// <returns></returns>
        public static string LeachExp(string Str, string ExpStr)
        {
            if (Str == null | string.IsNullOrEmpty(Str)) return "";
            string pattern = ExpStr;
            Regex Re = new Regex(pattern, RegexOptions.IgnoreCase);
            Str = Re.Replace(Str, "");
            Str = StringHelper.Trim(Str);
            return Str;
        }
        #endregion


    }
}
